﻿namespace Atomic.Mvc.ModelBinders
{
    using System.Web.Mvc;

    using Atomic.Extensions;
    using Atomic.Mvc.Validators;

    /// <summary>
    /// 扩展模型绑定器基类。
    /// </summary>
    public abstract class ModelBinderProviderBase : IModelBinder
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = this.OnBindModel(controllerContext, bindingContext);

            var validator = EntityValidator.Current.Validate(model);

            if (validator != null && !validator.IsValid())
            {
                validator.GetInvalidMessages().ForEach(error => bindingContext.ModelState.AddModelError(error.PropertyName ?? error.Key, error.Message));
            }

            return model;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        protected abstract object OnBindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);
    }
}